package com.dc.base.view.recyclerview

import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.view.View
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView

class LinearLayoutItemDecoration(context: Context, drawableResId: Int): RecyclerView.ItemDecoration() {

    private val mDivider: Drawable?

    init {
        mDivider = ContextCompat.getDrawable(context, drawableResId)
    }

    /**
     * 留出分割线位置
     *
     * @param outRect Rect
     * @param view    View
     * @param parent  RecyclerView
     * @param state   RecyclerView
     */
    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val position = parent.getChildAdapterPosition(view)
        if (position != 0) {
//            outRect.top = mDrawable.getIntrinsicHeight();
            outRect.set(0, mDivider!!.intrinsicHeight, 0, 0)
        }
    }

    override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) {
        val childCount = parent.childCount
        val rect = Rect()
        rect.left = parent.paddingLeft
        rect.right = parent.width - parent.paddingRight
        for (i in 1 until childCount) {
            rect.bottom = parent.getChildAt(i).top
            rect.top = rect.bottom - mDivider!!.intrinsicHeight
            mDivider.bounds = rect
            mDivider.draw(canvas)
        }
    }
}